/**
 * @作者 faner
 * @创建时间 2020/11/17 18:28
 */
package com.faner.fast.util;

import com.faner.fast.constant.enums.CodeEnum;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;

@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class R<T> implements Serializable {
    @Getter
    @Setter
    private int code;

    @Getter
    @Setter
    private String msg;

    @Getter
    @Setter
    private String path;

    @Getter
    @Setter
    private T data;

    public static <T> R<T> ok() {
        return restResult(null, CodeEnum.SUCCESS.getCode(), CodeEnum.SUCCESS.getMessage());
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, CodeEnum.SUCCESS.getCode(), CodeEnum.SUCCESS.getMessage());
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, CodeEnum.SUCCESS.getCode(), msg);
    }

    public static <T> R<T> failed() {
        return restResult(null, CodeEnum.FAIL.getCode(), CodeEnum.FAIL.getMessage());
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, CodeEnum.FAIL.getCode(), msg);
    }

    public static <T> R<T> failed(T data) {
        return restResult(data, CodeEnum.FAIL.getCode(), CodeEnum.FAIL.getMessage());
    }

    public static <T> R<T> failed(T data, String msg) {
        return restResult(data, CodeEnum.FAIL.getCode(), msg);
    }

    /**
     * 未授权返回结果
     */
    public static <T> R<T> forbidden(T data) {
        return restResult(data, CodeEnum.FAIL_ACL_DENY.getCode(), CodeEnum.FAIL_ACL_DENY.getMessage());
    }
    /**
     * 未登录返回结果
     */
    public static <T> R<T> unauthorized(T data) {
        return restResult(data, CodeEnum.FAIL_NEED_LOGIN.getCode(), CodeEnum.FAIL_NEED_LOGIN.getMessage());
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }
}
